package com.snail.clouds.storage.providers.tianyi_tv;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

/**
 * 二维码生成工具类
 */
public class QRCodeGenerator {
    
    private static final int QR_CODE_WIDTH = 500;
    private static final int QR_CODE_HEIGHT = 500;
    private static final String QR_CODE_FORMAT = "PNG";
    
    /**
     * 生成二维码图片
     * @param text 二维码内容
     * @return 二维码图片的字节数组
     * @throws WriterException 写入异常
     * @throws IOException IO异常
     */
    public static byte[] generateQRCode(String text) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, QR_CODE_WIDTH, QR_CODE_HEIGHT);
        
        BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
        
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, QR_CODE_FORMAT, byteArrayOutputStream);
        
        return byteArrayOutputStream.toByteArray();
    }
    
    /**
     * 生成二维码图片并保存到文件
     * @param text 二维码内容
     * @param filePath 保存文件路径
     * @return 保存的文件路径
     * @throws WriterException 写入异常
     * @throws IOException IO异常
     */
    public static String generateQRCodeToFile(String text, String filePath) throws WriterException, IOException {
        byte[] imageData = generateQRCode(text);
        
        Path path = Paths.get(filePath);
        // 确保目录存在
        if (path.getParent() != null) {
            Files.createDirectories(path.getParent());
        }
        
        Files.write(path, imageData);
        return path.toAbsolutePath().toString();
    }
    
    /**
     * 生成二维码图片并保存到临时文件
     * @param text 二维码内容
     * @return 保存的文件路径
     * @throws WriterException 写入异常
     * @throws IOException IO异常
     */
    public static String generateQRCodeToTempFile(String text) throws WriterException, IOException {
        String tempDir = System.getProperty("java.io.tmpdir");
        String fileName = "qrcode_" + System.currentTimeMillis() + ".png";
        return generateQRCodeToFile(text, tempDir + File.separator + fileName);
    }
    
    /**
     * 在控制台显示二维码（使用ASCII字符）
     * @param text 二维码内容
     * @throws WriterException 写入异常
     */
    public static void displayQRCodeInConsole(String text) throws WriterException {
        try {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, 8, 8);
            
            System.out.println("\n==================== 二维码 ====================");
            System.out.println("请使用天翼TV客户端扫描以下二维码进行登录:");
            System.out.println("二维码内容: " + text);
            System.out.println();
            
            // 简单的ASCII表示
            for (int y = 0; y < bitMatrix.getHeight(); y++) {
                for (int x = 0; x < bitMatrix.getWidth(); x++) {
                    System.out.print(bitMatrix.get(x, y) ? "██" : "  ");
                }
                System.out.println();
            }
            System.out.println("================================================\n");
            
        } catch (WriterException e) {
            throw e;
        }
    }
    
    /**
     * 生成二维码并创建HTML文件显示
     * @param text 二维码内容
     * @return HTML文件路径
     * @throws WriterException 写入异常
     * @throws IOException IO异常
     */
    public static String generateQRCodeHTML(String text) throws WriterException, IOException {
        // 1. 生成二维码图片
        byte[] imageData = generateQRCode(text);
        String base64Image = Base64.getEncoder().encodeToString(imageData);
        
        // 2. 创建HTML内容
        String htmlContent = "<!DOCTYPE html>\n" +
                "<html>\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>天翼TV登录二维码</title>\n" +
                "    <style>\n" +
                "        body {\n" +
                "            display: flex;\n" +
                "            flex-direction: column;\n" +
                "            justify-content: center;\n" +
                "            align-items: center;\n" +
                "            height: 100vh;\n" +
                "            margin: 0;\n" +
                "            font-family: Arial, sans-serif;\n" +
                "            background-color: #f5f5f5;\n" +
                "        }\n" +
                "        .container {\n" +
                "            text-align: center;\n" +
                "            background-color: white;\n" +
                "            padding: 20px;\n" +
                "            border-radius: 10px;\n" +
                "            box-shadow: 0 2px 10px rgba(0,0,0,0.1);\n" +
                "        }\n" +
                "        .qr-code {\n" +
                "            margin: 20px 0;\n" +
                "        }\n" +
                "        .qr-code img {\n" +
                "            border: 1px solid #ddd;\n" +
                "            border-radius: 5px;\n" +
                "        }\n" +
                "        .info {\n" +
                "            margin-top: 20px;\n" +
                "            color: #666;\n" +
                "        }\n" +
                "        .refresh {\n" +
                "            margin-top: 20px;\n" +
                "        }\n" +
                "        button {\n" +
                "            background-color: #4CAF50;\n" +
                "            color: white;\n" +
                "            padding: 10px 20px;\n" +
                "            border: none;\n" +
                "            border-radius: 5px;\n" +
                "            cursor: pointer;\n" +
                "            font-size: 16px;\n" +
                "        }\n" +
                "        button:hover {\n" +
                "            background-color: #45a049;\n" +
                "        }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "    <div class=\"container\">\n" +
                "        <h1>天翼TV登录二维码</h1>\n" +
                "        <div class=\"qr-code\">\n" +
                "            <img src=\"data:image/png;base64," + base64Image + "\" alt=\"登录二维码\" />\n" +
                "        </div>\n" +
                "        <div class=\"info\">\n" +
                "            <p>请使用天翼TV客户端扫描上方二维码进行登录</p>\n" +
                "            <p>二维码URL: <a href=\"" + text + "\" target=\"_blank\">" + text + "</a></p>\n" +
                "        </div>\n" +
                "        <div class=\"refresh\">\n" +
                "            <button onclick=\"window.location.reload()\">刷新二维码</button>\n" +
                "        </div>\n" +
                "    </div>\n" +
                "</body>\n" +
                "</html>";
        
        // 3. 确保目录存在
        String tempDir = System.getProperty("user.dir") + File.separator + "temp" + File.separator + "qrcode";
        Path tempPath = Paths.get(tempDir);
        Files.createDirectories(tempPath);
        
        // 4. 写入HTML文件
        String htmlFilePath = tempDir + File.separator + "qrcode.html";
        Files.write(Paths.get(htmlFilePath), htmlContent.getBytes());
        
        return htmlFilePath;
    }
}